#include "include.h"
#include "config.h"
#include "systick.h"
#include "output.h"

static uint16_t output_status = 0;

bit     h1 = 0;
bit     h2 = 0;
uint8_t fan = 0;
uint8_t fan_last = 0;

#define RY1 P26
#define RY2 P27
#define RY3 P02
#define RY4 P03
#define RY5 P31
#define RY6 P30

#define H1_L1  RY1
#define H1_L2  RY3
#define H2_L1  RY2
#define H2_L2  RY4
#define FAN_LO RY6
#define FAN_HI RY5

output_status_t  out_status;
static uint32_t delay_open_time = 0;

static uint32_t h1_runtime;
static uint32_t h2_runtime;
static uint32_t fan_runtime;
static uint32_t h1_stoptime;
static uint32_t h2_stoptime;
static uint32_t fan_stoptime;

void output_func(void){

	if(fan != fan_last){
		reset_ltime(&delay_open_time);
		FAN_LO = 0;
		FAN_HI = 0;
		fan_last = fan;
	}
	else if(is_ltime_out(delay_open_time, sec(1))){
		if(fan == HIGH_SPEED)      {FAN_HI = 1; FAN_LO = 0;out_status.is_fan_running = 1;}
		else if(fan == LOW_SPEED)  {FAN_HI = 0; FAN_LO = 1;out_status.is_fan_running = 1;}
		else                       {FAN_HI = 0; FAN_LO = 0;out_status.is_fan_running = 0;}
	}
	if(!out_status.is_fan_running)
		reset_ltime(&fan_runtime);
	else if(out_status.is_fan_running)
		reset_ltime(&fan_stoptime);
	
	
//-------------------------------------
	if(h1 == ON){
		H1_L1 = H1_L2 = 1;
		out_status.is_h1_running = 1;
	}
	else{
		H1_L1 = H1_L2 = 0;
		out_status.is_h1_running = 0;
	}
	if(!out_status.is_h1_running)
		reset_ltime(&h1_runtime);
	else if(out_status.is_h1_running)
		reset_ltime(&h1_stoptime);

//--------------------------------------
	if(h2 == ON){
		H2_L1 = H2_L2 = 1;
		out_status.is_h2_running = 1;
	}
	else{
		H2_L1 = H2_L2 = 0;
		out_status.is_h2_running = 0;
	}
	if(!out_status.is_h2_running)
		reset_ltime(&h2_runtime);
	else if(out_status.is_h2_running)
		reset_ltime(&h2_stoptime);
//---------------------------------------

	__CF_H01 = (uint16_t)h1;
	__CF_H02 = (uint16_t)h2;
	__CF_FAN = (uint16_t)fan;
}

void set_out(enum output_type out_t, uint8_t status){
	if(out_t == H1){
		if(status) h1 = 1;
		else       h1 = 0;
	}
	else if(out_t == H2){
		if(status) h2 = 1;
		else       h2 = 0;
	}
	else if(out_t == FAN){
		fan = status;
	}
	
}
/*
//-----------------------------------------------
uint32_t get_output_runtime(enum output_type s){
	if(s == H1){
		if(out_status.is_h1_running)
			return(get_curr_ltime() - h1_runtime);
	}
	else if(s == H2){
		if(out_status.is_h2_running)
			return(get_curr_ltime() - h2_runtime);
	}
	else if(s == FAN){
		if(out_status.is_fan_running)
			return(get_curr_ltime() - fan_runtime);
	}
	return 0;
}*/
//-----------------------------------------------
uint32_t get_output_stoptime(enum output_type s){
	/*
	if(s == H1){
		if(!out_status.is_h1_running)
			return(get_curr_ltime() - h1_stoptime);
	}
	else if(s == H2){
		if(!out_status.is_h2_running)
			return(get_curr_ltime() - h2_stoptime);
	}
	*/
	if(s == FAN){
		if(!out_status.is_fan_running)
			return(get_curr_ltime() - fan_stoptime);
	}
	return 0;
}